package com.rg.dao;

import com.rg.model.OrderItemsModel;
import com.rg.model.OrderModel;
import com.rg.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

//数据访问对象类，用于订单相关的数据库操作。
//insertOrder和insertOrderItems方法用于插入订单数据和订单项数据。
public class Orderdao {
    /**
     * 插入订单数据表*
     */
    public void insertOrder(Connection conn, OrderModel order) {
        try {
            String sql = "INSERT INTO `order` (total, amount, status, paytype, name, phone, address, datetime, user_id) VALUES (?,?,?,?,?,?,?,?,?);";
            QueryRunner queryRunner = new QueryRunner();
            Object params[] = {
                    order.getTotal(),
                    order.getAmount(), 0, 1, order.getName(),
                    order.getPhone(), order.getAddress(),
                    order.getDatetime(), order.getUser().getUserId()};
            queryRunner.update(conn, sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 将数据插入订单项*
     */
    public void insertOrderItems(Connection conn, OrderItemsModel item) {
        try {
            String sql = "insert into orderitem(price,amount,goods_id,order_id) values(?,?,?,?)";
            QueryRunner queryRunner = new QueryRunner();
            Object param[] = {item.getPrice(), item.getAmount(), item.getGoods().getGoodsId(), item.getOrder().getId()};
            queryRunner.update(conn, sql, param);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public int getLastInsertId(Connection con) throws SQLException {
        QueryRunner r = new QueryRunner();
        String sql = "select last_insert_id()";
        BigInteger bi = r.query(con, sql,new ScalarHandler<BigInteger>());
        return Integer.parseInt(bi.toString());
    }
    public List<OrderModel> selectAll(int userid) throws SQLException {
        QueryRunner r = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from `order` where user_id=? order by datetime desc";
        return r.query(sql, new BeanListHandler<OrderModel>(OrderModel.class),userid);
    }
    public List<OrderItemsModel> selectAllItem(int orderid) throws SQLException{
        QueryRunner r = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select i.id,i.price,i.amount,g.goods_name from orderitem i,goods g where id=? and i.goods_id=g.goods_id";
        return r.query(sql, new BeanListHandler<OrderItemsModel>(OrderItemsModel.class),orderid);
    }
}

